-module(udp_packet_fun).
-include("protocol.hrl").
-export[do/2,do/1,parse/1,start/0,start_link/0].

-define(SERVER,?MODULE).

-record(udp_counter,{
		packet_counter = 0,
		unicast_counter = 0,
		ip_counter = 0,
		unknown_counter = 0
		}).
start() ->
	parser_eng:start(fun do/2).
	
start_link() ->
	parser_eng:start_link(fun do/2).

parse(Packet_Tuple) ->
	gen_server:cast(?SERVER,{packet_comming,Packet_Tuple}).
	
do(stop) ->
	gen_server:call(?SERVER,stop);
do(report) ->
	Counter = gen_server:call(?SERVER,report),
	io:format("Udp Counter ~n ~p ~n",[Counter]);
do(reset_counter) ->
	gen_server:call(?SERVER,reset_counter).
	
	
do(get,protocol_id) ->
	?SERVER;
	
do(init,_) ->
	#udp_counter{};
do(report,State) ->
	State;
do(reset,State) ->
	#udp_counter{};
do(packet_comming,{P_Tuple,Counter}) ->
	case P_Tuple#packet_tuple.packet of
	<<SPort:16/integer,DPort:16/integer,Length:16/integer,CheckSum:16/integer,Payload/binary>> ->
		packet_dispatch:do(packet_dispatch:protocol_lookup(udp_protocol,{SPort,DPort}),
					P_Tuple#packet_tuple{packet=Payload,size=Length,context=[#udp_protocol{source_port=SPort,dest_port=DPort} | P_Tuple#packet_tuple.context]}),
		Counter#udp_counter{unicast_counter = Counter#udp_counter.unicast_counter + 1,
									   ip_counter = Counter#udp_counter.ip_counter + 1,
									   packet_counter = Counter#udp_counter.packet_counter + 1};
	_ ->
		Counter#udp_counter{unknown_counter = Counter#udp_counter.unknown_counter + 1,
									   packet_counter = Counter#udp_counter.packet_counter + 1}
	end;
do(_,_) ->
	undef.
	

